import { constantRoutes } from '@/router/index.js'
import Layout from '@/layout/index.vue'
import {defineAsyncComponent} from 'vue'

const permission = {
  state: {
    routers: constantRoutes,
    addRouters: [],
    hasLoad: false,
  },
  mutations: {
    SET_ROUTERS: (state, routers) => {
      state.addRouters = routers
      state.routers = constantRoutes.concat(routers)
    },
    SET_LOAD: (state, hasLoad) => {
      state.hasLoad = hasLoad
    },
  },
  actions: {
    GenerateRoutes ({ commit }, asyncRouter) {
      commit('SET_ROUTERS', asyncRouter)
    },
  },
}

export const filterAsyncRouter = (routers) => {
  return routers.filter((router) => {
    if (router.resourceType === 'catalog') {
      // 菜单节点，添加Layout父容器
      router.component = Layout
    } else {
      // const component = router.component
      router.component = loadView(router.path)
    }
    if (router.children && router.children.length) {
      router.children = filterAsyncRouter(router.children)
    }
    return true
  })
}

const modules = import.meta.glob('@/views/**/*.vue', { eager: true, import: 'default' })
export const loadView = (view) => {
  let res;
  for (const path in modules) {
    const dir = path.split('views')[1].split('.vue')[0];
    if (dir === view || dir === view + '/index') {
      res = modules[path]
    }
  }
  return res;
}

export default permission
